﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Data;
//using Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Core;
using System.Security.Cryptography;

namespace CRM.UTIL
{
    /// <summary>
    /// 常用方法
    /// XXXXXXXXX
    /// 2013.10.14
    /// </summary>
    public class Common
    {
        // public static string ConnectionString = ConfigurationManager.ConnectionStrings["CRM"].ConnectionString;




        #region 系统中的枚举值
        public enum DBAction
        {
            Insert,
            Update,
            Delete
        }
        #endregion

        #region 系统中的默认值
        /// <summary>
        /// 默认分页大小
        /// </summary>
        public const string DefaultPageSize = "15";

        /// <summary>
        /// 默认当前页为第一页

        /// </summary>
        public const string DefaultCurrentPageIndex = "1";
        #endregion

        #region 加解密字串
        public static System.Random ran = new Random();
        /// <summary>
        /// 用于加密的 Key
        /// </summary>
        public const string strKey = "@s\t2d";
        /// <summary>
        /// 加密字串
        /// </summary>
        /// <param name="srcStr">原字串</param>
        public static string EncryptString(string srcStr)
        {
            //			System.Random ran = new System.Random();
            //			ran.Next();
            string val = "";
            try
            {
                System.Text.UTF8Encoding u8 = new System.Text.UTF8Encoding();
                int i = ran.Next(1, 6500);
                int j = ran.Next(i, 75000);
                byte[] bt = u8.GetBytes(
                    i.ToString() + strKey
                    + srcStr
                    + strKey + j.ToString()
                    );
                val = System.Convert.ToBase64String(bt);
            }
            catch { val = ""; }
            return val;
        }

        /// <summary>
        /// 解密字串
        /// </summary>
        /// <param name="decStr">加密过的字串</param>
        public static string DecryptString(string decStr)
        {
            string val = "";
            try
            {
                if (decStr == null || decStr == "")
                { return ""; }
                byte[] bt = System.Convert.FromBase64String(decStr);
                System.Text.UTF8Encoding u8 = new System.Text.UTF8Encoding();
                string str = u8.GetString(bt);
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(strKey);
                string[] tm = reg.Split(str);
                val = tm[1];
            }
            catch
            {
            }
            return val;
        }

        #endregion

        #region 数据库字段空值处理
        /// <summary>
        /// 将空值 "" 转换成数据库的 null,将单引号转换成两个连续的单引号

        /// </summary>
        public static object TransQuote(object str)
        {
            if (str == null || str.Equals(""))
            {
                return System.DBNull.Value;
            }
            else
            {
                if (str.ToString().IndexOf("'") >= 0) //若存在单引号
                {
                    str = str.ToString().Replace("'", "''");
                }
                return str;
            }
        }


        /// <summary>
        /// 将空值 "" 转换成数据库的 null
        /// </summary>
        public static object TransValue(object str)
        {
            if (str == null || str.Equals(""))
            {
                return System.DBNull.Value;
            }
            else
            {
                return str;
            }
        }

        /// <summary>
        /// 将空值 "" 设定成指定的默认值

        /// </summary>
        /// <param name="str">传入值</param>
        /// <param name="val">默认值</param>
        public static object TransValue(object str, object val)
        {
            if (str == null || str.Equals(""))
            {
                return val;
            }
            else
            {
                return str;
            }
        }
        #endregion


        #region 获取 Mail 地址集合
        /// <summary>
        /// 根据字串，获取 Mail 地址集合
        /// XXXXXXXXX
        /// </summary>
        /// <param name="addr"></param>
        public static System.Net.Mail.MailAddress[] CollectAddress(string addr)
        {
            List<System.Net.Mail.MailAddress> list = new List<System.Net.Mail.MailAddress>();

            string[] arr = addr.Split(",;".ToCharArray());
            foreach (string str in arr)
            {
                if (!String.IsNullOrEmpty(str))
                {
                    list.Add(GetAddress(str));
                }
            }
            return list.ToArray();
        }


        /// <summary>
        /// 根据“管理员&lt;bpmmaster@coastal.com.cn&gt;”格式获取 MailAddress
        /// </summary>
        /// <param name="addr"></param>
        public static System.Net.Mail.MailAddress GetAddress(string addr)
        {
            if (String.IsNullOrEmpty(addr)) { return null; }
            try
            {
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
                System.Net.Mail.MailAddress ma = new System.Net.Mail.MailAddress(reg.Match(addr).Value, "IT小助手");
                return ma;
            }
            catch
            {
                return null;
            }
        }
        #endregion


        #region 写入日志文件
        /// <summary>
        /// 记录错误
        /// XXXXXXXXX
        /// </summary>
        /// <param name="msg">出错信息</param>
        /// <param name="folio">流程编号</param>
        /// <param name="activ">节点名称</param>
        /// <param name="act">执行的动作</param>
        /// <param name="usr">执行人姓名</param>
        public static void LogErrorMsg(string msg, string usr)
        {
            string logXml = "";

            if (string.IsNullOrEmpty(msg)) msg = "";
            if (string.IsNullOrEmpty(usr)) usr = "";

            string fileName = System.DateTime.Now.ToString("yyyyMM") + ".xml";
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "Log\\"))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "Log\\");
            }
            string fullName = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + fileName;
            logXml = fullName;
            System.Xml.XmlDocument x_doc = new System.Xml.XmlDocument();//写入到日志文件的内容
            if (System.IO.File.Exists(fullName))
            {
                x_doc.Load(fullName);
            }
            else
            {
                x_doc.LoadXml("<Logs />");
            }

            logXml = fullName;//国祥调试





            XmlElement x_f = x_doc.CreateElement("ErrorMsg");
            System.Xml.XmlElement x_ele = x_doc.CreateElement("LogDateTime");
            XmlText x_txt = x_doc.CreateTextNode(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            x_ele.AppendChild(x_txt);		//时间
            x_f.AppendChild(x_ele);

            x_ele = x_doc.CreateElement("ErrorMsg");
            x_txt = x_doc.CreateTextNode(msg.Replace("<", "").Replace(">", ""));
            x_ele.AppendChild(x_txt);		//错误信息
            x_f.AppendChild(x_ele);




            if (x_doc.DocumentElement.ChildNodes.Count == 0)
            { x_doc.DocumentElement.AppendChild(x_f); }
            else { x_doc.DocumentElement.InsertBefore(x_f, x_doc.DocumentElement.FirstChild); }
            x_doc.Save(fullName);

        }
        #endregion

        #region 邮件发送
        public static void mailsend(string to, string cc, string subject, string body, ref string message)
        {
            message = "";
            CRM.UTIL.MailSend mail = new UTIL.MailSend();
            mail.To = to.Trim();
            mail.Cc = cc.Trim();
            mail.Subject = subject.Trim();
            mail.Body = body;
            message = mail.AsyncSend().ToString();
        }
        #endregion

        #region Office2HTML
        /// <summary>
        /// Word转成Html
        /// </summary>
        /// <param name="path">要转换的文档的路径</param>
        /// <param name="savePath">转换成html的保存路径</param>
        /// <param name="wordFileName">转换成html的文件名字</param>
        public static void Word2Html(string path, string savePath, string wordFileName)
        {

            //Word.ApplicationClass word = new Word.ApplicationClass();
            //Type wordType = word.GetType();
            //Word.Documents docs = word.Documents;
            //Type docsType = docs.GetType();
            //Word.Document doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { (object)path, true, true });
            //Type docType = doc.GetType();
            //string strSaveFileName = savePath + wordFileName + ".html";
            //object saveFileName = (object)strSaveFileName;
            //docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML });
            //docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
            //wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);

        }
        /// <summary>
        /// Excel转成Html
        /// </summary>
        /// <param name="path">要转换的文档的路径</param>
        /// <param name="savePath">转换成html的保存路径</param>
        /// <param name="wordFileName">转换成html的文件名字</param>
        public static void Excel2Html(string path, string savePath, string wordFileName)
        {
            string str = string.Empty;
            Microsoft.Office.Interop.Excel.Application repExcel = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook workbook = null;
            Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
            workbook = repExcel.Application.Workbooks.Open(path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
            object htmlFile = savePath + wordFileName + ".html";
            object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
            workbook.SaveAs(htmlFile, ofmt, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            object osave = false;
            workbook.Close(osave, Type.Missing, Type.Missing);
            repExcel.Quit();
        }
        ///// <summary>
        ///// ppt转成Html
        ///// </summary>
        ///// <param name="path">要转换的文档的路径</param>
        ///// <param name="savePath">转换成html的保存路径</param>
        ///// <param name="wordFileName">转换成html的文件名字</param>
        //public static void PPT2Html(string path, string savePath, string wordFileName)
        //{
        //    Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();
        //    string strSourceFile = path;
        //    string strDestinationFile = savePath + wordFileName + ".html";
        //    Microsoft.Office.Interop.PowerPoint.Presentation prsPres = ppApp.Presentations.Open(strSourceFile, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);

        //    prsPres.SaveAs(strDestinationFile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoTrue);
        //    prsPres.Close();
        //    ppApp.Quit();
        //}
        //#endregion

        #region
        public static int getWeekNumInMonth(DateTime daytime)
        {
            var dayInMonth = daytime.Day;
            //本月第一天
            var firstDay = daytime.AddDays(1 - daytime.Day);
            //本月第一天是周几
            var weekday = (int)firstDay.DayOfWeek == 0 ? 7 : (int)firstDay.DayOfWeek;
            //本月第一周有几天
            var firstWeekEndDay = 7 - (weekday - 1);
            //当前日期和第一周之差
            var diffday = dayInMonth - firstWeekEndDay;
            diffday = diffday > 0 ? diffday : 1;
            //当前是第几周,如果整除7就减一天
            var weekNumInMonth = ((diffday % 7) == 0
                ? (diffday / 7 - 1)
                : (diffday / 7)) + 1 + (dayInMonth > firstWeekEndDay ? 1 : 0);
            return weekNumInMonth;
        }

        /// <summary>  
        /// 获取指定月份指定周数的开始日期  
        /// </summary>  
        /// <param name="year">年份</param>  
        /// <param name="month">月份</param>  
        /// <param name="index">周数</param>  
        /// <returns></returns>  
        public static DateTime GetStartDayOfWeeks(int year, int month, int index)
        {
            if (year < 1600 || year > 9999)
            {
                return DateTime.MinValue;
            }
            if (month < 0 || month > 12)
            {
                return DateTime.MinValue;
            }
            if (index < 1)
            {
                return DateTime.MinValue;
            }
            DateTime startMonth = new DateTime(year, month, 1);  //该月第一天  
            int dayOfWeek = 7;
            if (Convert.ToInt32(startMonth.DayOfWeek.ToString("d")) > 0)
                dayOfWeek = Convert.ToInt32(startMonth.DayOfWeek.ToString("d"));  //该月第一天为星期几  
            DateTime startWeek = startMonth.AddDays(1 - dayOfWeek);  //该月第一周开始日期  
            //DateTime startDayOfWeeks = startWeek.AddDays((index - 1) * 7);  //index周的起始日期  
            DateTime startDayOfWeeks = startWeek.AddDays((index - 1) * 7);  //index周的起始日期  
            if ((startDayOfWeeks - startMonth.AddMonths(1)).Days > 0)  //startDayOfWeeks不在该月范围内  
            {
                //MessageBox.Show("输入周数大于本月最大周数");
                return DateTime.MinValue;
            }
            return startDayOfWeeks;
        }

        /// <summary>
        /// 获取当前时间是第几季度
        /// </summary>
        /// <param name="daytime"></param>
        /// <returns></returns>
        public static int GetQuarterOfYear(DateTime datetime)
        {
            return (datetime.Month + 2) / 3;
        }

        /// <summary>
        /// 获取任务汇报项中time_String字段编码
        /// </summary>
        /// <param name="type">汇报类型（0：周汇报；1：月汇报；2：季度汇报）</param>
        /// <returns></returns>
        public static string GetTimeStringByType(string type, DateTime datetime)
        {
            string timeString = "";
            switch (type)
            {
                case "0": timeString = datetime.Year.ToString() + "-" + datetime.Month.ToString() + "-" + Common.getWeekNumInMonth(datetime).ToString();
                    break;
                case "1": timeString = datetime.Year.ToString() + "-" + datetime.Month.ToString();
                    break;
                case "2": timeString = datetime.Year.ToString() + "-" + Common.GetQuarterOfYear(datetime).ToString();
                    break;
                default:
                    break;
            }

            return timeString;
        }
        #endregion

        /// <summary>
        /// 传入存储过程的多个参数
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string GetParamGroup(string param)
        {
            string result = "";
            string[] tems = param.Split(',');
            foreach (var tem in tems)
            {
                result += "'" + tem + "',";
            }
            result = result.TrimEnd(',');
            return result;
        }
        public static string encryptKey = "Oyea";    //定义密钥  

        #region 加密字符串
        /// <summary> /// 加密字符串   
        /// </summary>  
        /// <param name="str">要加密的字符串</param>  
        /// <returns>加密后的字符串</returns>  
        public static string JiaMi(string str)
        {
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();   //实例化加/解密类对象   

            byte[] key = Encoding.Unicode.GetBytes(encryptKey); //定义字节数组，用来存储密钥    

            byte[] data = Encoding.Unicode.GetBytes(str);//定义字节数组，用来存储要加密的字符串  

            MemoryStream MStream = new MemoryStream(); //实例化内存流对象      

            //使用内存流实例化加密流对象   
            CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);

            CStream.Write(data, 0, data.Length);  //向加密流中写入数据      

            CStream.FlushFinalBlock();              //释放加密流      

            return Convert.ToBase64String(MStream.ToArray());//返回加密后的字符串  
        }
        #endregion

        #region 解密字符串
        /// <summary>  
        /// 解密字符串   
        /// </summary>  
        /// <param name="str">要解密的字符串</param>  
        /// <returns>解密后的字符串</returns>  
        public static string JieMi(string str)
        {
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();   //实例化加/解密类对象    

            byte[] key = Encoding.Unicode.GetBytes(encryptKey); //定义字节数组，用来存储密钥    

            byte[] data = Convert.FromBase64String(str);//定义字节数组，用来存储要解密的字符串  

            MemoryStream MStream = new MemoryStream(); //实例化内存流对象      

            //使用内存流实例化解密流对象       
            CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);

            CStream.Write(data, 0, data.Length);      //向解密流中写入数据     

            CStream.FlushFinalBlock();               //释放解密流      

            return Encoding.Unicode.GetString(MStream.ToArray());       //返回解密后的字符串  
        }
        #endregion
        #endregion

        public static bool CanExportAllData(string account)
        {
            var flag = false;
            var arr = ConfigurationManager.AppSettings["CanExportAllData"].Split(',');
            foreach (var str in arr)
            {
                if (!String.Equals(str.Trim(), account.Trim(), StringComparison.CurrentCultureIgnoreCase)) continue;
                flag = true;
                break;
            }
            return flag;
        }
    }

}
